import React, { CSSProperties, useState, useEffect } from 'react'
import { List, Image, SearchBar, InfiniteScroll } from 'antd-mobile'
import {
  List as VirtualizedList,
  AutoSizer,
  WindowScroller
} from 'react-virtualized'
import { goods } from '../../type/home'
import { getGoodsList } from '../../api/home'
import { useHistory } from 'react-router-dom'

export default () => {
  const [goodData, setGood] = useState([] as goods[])
  const [page, setPage] = useState({
    count: 0,
    limitNum: 10
  })
  const [hasMore, setHasMore] = useState(true)
  const history = useHistory()
  const [brand, setBrand] = useState('')
  const getData = async () => {
    // const res = await getGoodsList({ ...page, count: page.count++ })
    const res = await getGoodsList(page)
    setGood(res.data)
    console.log(res.data)
  }

  const loadMore = async () => {
    const res = await getGoodsList({ ...page, count: page.count++ })
    setGood([...goodData, ...res.data])
    setHasMore(res.data.length > 0)
  }

  function rowRenderer ({
    index,
    key,
    style
  }: {
    index: number
    key: string
    style: CSSProperties
  }) {
    const item = goodData[index]
    if (!item) return
    return (
      <List.Item
        key={key}
        style={style}
        prefix={
          <Image
            src={item.img1}
            style={{ borderRadius: 20 }}
            fit='cover'
            width={60}
            height={60}
          />
        }
        description={item.originprice}
        onClick={() => {
          history.push(`/detail?proid=${item.proid}`)
        }}
      >
        {item.proname}
      </List.Item>
    )
  }

  return (
    <div>
      <div
        className='header'
        style={{
          background: '#c82519',
          width: '375px',
          height: '50px',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center'
        }}
      >
        <SearchBar
          placeholder='请输入内容'
          value={brand}
          style={{ width: '300px', '--border-radius': '20px' }}
        />
      </div>
      <WindowScroller>
        {({ height, scrollTop, isScrolling }) => (
          <List>
            <AutoSizer disableHeight>
              {({ width }) => (
                <VirtualizedList
                  autoHeight
                  rowCount={goodData.length}
                  rowRenderer={rowRenderer}
                  width={width}
                  height={height}
                  rowHeight={120}
                  overscanRowCount={10}
                  isScrolling={isScrolling}
                  scrollTop={scrollTop}
                />
              )}
            </AutoSizer>
          </List>
        )}
      </WindowScroller>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
  )
}
